﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;
using HCRS.Implementation;
using System.IO;
using System.Net.Mail;
using System.Text;
using Common;
namespace EZCRS.HCMS.DataAcl
{
    /// <summary>
    /// FGBUserSystems 的摘要说明
    /// </summary>
    public class FGBUserSystems
    {
        /// <summary>
        /// 校验方式字符串，存储过程使用参数
        /// </summary>
        static string[] ValidateTypeString = new string[] { "username", "email", "mobile", "cardnumber" };
        public FGBUserSystems()
        {
        }

        #region 用户注册
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="gid">集团ID</param>
        /// <param name="orgtype">用户类型</param>
        /// <param name="username">用户名</param>
        /// <param name="usrpassword">用户密码</param>
        /// <param name="usremail">用户邮箱</param>
        /// <param name="usrmobile">用户手机号</param>
        /// <param name="question">安全问题</param>
        /// <param name="answer">安全问题答案</param>
        /// <param name="ademail">是否接受邮件促销信息</param>
        /// <param name="admobile">是否接受手机短信促销信息</param>
        /// <param name="msg">输出信息</param>
        /// <returns>是否成功注册</returns>
        public static bool hfg_userInsert(int gid, string username, string usrpassword, string usremail, string usrmobile, bool ademail, bool admobile, string guid, bool IsAjax, out string msg)
        {
            msg = "";
            username = username.Trim();
            usremail = usremail.Trim();
            usrmobile = usrmobile.Trim();


            if (gid < 1 || username.Length < 5 || usrpassword.Length < 6 || usremail.Length < 5 || (usrmobile.Length > 0 && usrmobile.Length < 10))
            {
                msg = "注册失败,用户或电子邮箱或密码未填写或非正常方式注册！";
                return false;
            }
            if (CommonDataAccess.IsHack(username + usrpassword + usremail + usrmobile))
            {
                msg = "注册失败,提交信息非法!";
                return false;
            }
            if (IsExistUserName(gid, username))
            {
                msg += "注册失败,用户名已被使用!";

            }
            if (IsExistEmail(gid, usremail))
            {
                msg += "注册失败,电子邮箱已被使用!";

            }
            if (usrmobile.Length > 0 && IsExistMobile(gid, usrmobile))
            {
                msg += "注册失败,手机号已被使用!";

            }
            if (msg.Length > 0)
            {
                return false;
            }

            usrpassword = CommonWeb.ToMD5(usrpassword);
            //  answer = CommonWeb.ToMD5(answer);
            string usercheckcode = CommonWeb.ToMD5(guid);
            DateTime regdate = DateTime.Now;
            DateTime Checkcodedate = DateTime.Now;

            bool flag = CommonDataAccess.ExecInsertProcedure("HFG_hfg_user_Insert_Web", "@gid,@username,@email,@mobnumb,@pwd,@usercheckcode,@ademail,@admobile", "int,varchar,varchar,varchar,varchar,varchar,bit,bit", new object[] { gid, username, usremail, usrmobile, usrpassword, usercheckcode, ademail, admobile });
            if (flag)
            {
                msg = "成功注册!";
            }
            else
            {
                msg = "注册失败,用户或电子邮箱或手机号已存在";
            }
            return flag;
        }
        #endregion

        #region 校验唯一

        public static bool IsUserExist(int gid, string value, ValidateType vtype)
        {
            DataTable dt = CommonDataAccess.ExecProcedure("HFG_hfg_user_IsExist", "@gid,@value,@type", "int,varchar,varchar", new Object[] { gid, value, ValidateTypeString[(int)vtype] }, "");
            if (dt != null && dt.Rows[0][0].ToString() == "0")
            {
                return false;
            }
            return true;
        }

        #endregion

        #region 用户名是否存在
        /// <summary>
        /// 用户名是否存在
        /// </summary>
        /// <param name="gid"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public static bool IsExistUserName(int gid, string username)
        {
            return IsUserExist(gid, username, ValidateType.UserName);
        }
        #endregion

        #region 电子邮箱是否存在
        /// <summary>
        /// 电子邮箱是否存在
        /// </summary>
        /// <param name="gid"></param>
        /// <param name="usremail"></param>
        /// <returns></returns>

        public static bool IsExistEmail(int gid, string usremail)
        {
            return IsUserExist(gid, usremail, ValidateType.Email);
        }

        #endregion

        #region 手机号是否存在
        /// <summary>
        /// 手机号是否存在
        /// </summary>
        /// <param name="gid"></param>
        /// <param name="usrmobile"></param>
        /// <returns></returns>
        public static bool IsExistMobile(int gid, string usrmobile)
        {
            return IsUserExist(gid, usrmobile, ValidateType.Mobile);

        }
        #endregion

        #region 会员卡号是否已使用
        /// <summary>
        /// 会员卡号是否已使用
        /// </summary>
        /// <param name="usrmobile"></param>
        /// <param name="gid"></param>
        /// <returns></returns>
        public static bool IsExistCardNumber(int gid, string cardNumber)
        {
            return IsUserExist(gid, cardNumber, ValidateType.CardNumber);

        }
        #endregion

        #region 验证邮箱或密码链接
        /// <summary>
        /// 验证邮箱或密码链接
        /// </summary>
        /// <param name="gid">集团ID</param>
        /// <param name="username">用户名</param>
        /// <param name="type">类型(e:email|p:password)</param>
        /// <param name="cd">验证码</param>
        /// <returns></returns>
        public static bool IsValidateCode(int gid, string username, string type, string cd, out string md5cd)
        {
            cd = cd.Substring(1, cd.Length - 1);
            md5cd = CommonWeb.ToMD5(cd);
            int hours = CommonWeb.strToInt(FGBCommon.GetConfiguration("codecheckhours", "20"));
            DataTable dt = CommonDataAccess.ExecProcedure
                ("HFG_GetUserIsValidateCode",
                "@gid,@username,@checkcode,@type,@hours",
                "int,string,string,string,int",
                new object[] { gid, username, md5cd, type, hours }, "vv");
            if (dt != null && dt.Rows.Count == 1)
            {
                if (dt.Rows[0][0].ToString() == "1")
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 验证邮箱
        /// </summary>
        /// <param name="gid">集团ID</param>
        /// <param name="uid">用户ID</param>
        /// <param name="cd">校验码</param>
        /// <returns>是否成功</returns>
        public static bool IsValidateCode(int gid, int uid,string cd)
        {
            cd = cd.Substring(1, cd.Length - 1);
            cd = CommonWeb.ToMD5(cd);
            int hours = CommonWeb.strToInt(FGBCommon.GetConfiguration("codecheckhours", "20"));
             DataTable dt = CommonDataAccess.ExecProcedure
                ("HFG_GetEmailIsValidateCode",
                "@gid,@uid,@checkcode,@hours",
                "int,int,string,int",
                new object[] { gid, uid, cd,hours }, "vv");
            if (dt != null && dt.Rows.Count == 1)
            {
                if (dt.Rows[0][0].ToString() == "1")
                {
                    return true;
                }
            }
            return false;
        }

        #endregion

        #region 用户重设密码
        /// <summary>
        /// 用户重设密码
        /// </summary>
        /// <param name="gid">集团ID</param>
        /// <param name="username">用户名</param>
        /// <param name="cd">链接校验码</param>
        /// <param name="password">新密码</param>
        /// <returns>是否成功</returns>
        public static bool UserResetPassword(int gid, object username, string cd, string password)
        {
            password = CommonWeb.ToMD5(password);
            return CommonDataAccess.ExecUpdateProcedure
                ("HFG_UserResetPwd",
                "@gid,@username,@checkcode,@Pwd",
                "int,string,string,string",
                new object[] { gid, username, cd, password });
        }
        #endregion

        #region 用户信息校验
        /// <summary>
        /// 用户是否存在
        /// </summary>
        /// <param name="gid">集团ID</param>
        /// <param name="username">用户名</param>
        /// <param name="useremail">用户Email</param>
        /// <param name="mobile">用户手机号</param>
        /// <param name="pwd">加密后的密码（为空时校验登录）</param>
        /// <param name="uid">用户ID</param>
        /// <returns>是否存在</returns>
        public static bool UserIsExist(int gid, string username, string useremail, string mobile, string pwd, ValidateType vtype, out FGBUserClass userinfo)
        {
            userinfo = new FGBUserClass();
            if (pwd != "") pwd = CommonWeb.ToMD5(pwd);
            string param = "";
            if (vtype == ValidateType.UserName)
            {
                param = username;
            }
            else if (vtype == ValidateType.Email)
            {
                param = useremail;
            }
            else if (vtype == ValidateType.Mobile)
            {
                param = mobile;
            }
            else if (vtype == ValidateType.CardNumber)
            {
                param = username;
            }
            else
            {
                param = "~~~~~~~~~~";
            }

            DataTable dt = CommonDataAccess.ExecProcedure
                ("HFG_UserIsExist",
                "@gid,@username,@type",
                "int,string,int",
                new object[] { gid, param, (int)vtype }, "vv");
            if (dt != null && dt.Rows.Count == 1)
            {
                bool IsValidate = false;
                string u = dt.Rows[0]["username"].ToString();
                string p = dt.Rows[0]["usrpassword"].ToString();
                string e = dt.Rows[0]["usremail"].ToString();
                string m = dt.Rows[0]["usrmobile"].ToString();
                string c = dt.Rows[0]["cardnumber"].ToString();

                if (pwd.Length > 0)
                {
                    if (vtype == ValidateType.UserName)
                    {
                        IsValidate = (username == u && pwd == p);
                    }
                    else if (vtype == ValidateType.Email)
                    {
                        IsValidate = (useremail == e && pwd == p);
                    }
                    else if (vtype == ValidateType.Mobile)
                    {
                        IsValidate = (mobile == m && pwd == p);
                    }
                    else if (vtype == ValidateType.CardNumber)
                    {
                        IsValidate = (username == c && pwd == p);
                    }
                    else
                    {
                        IsValidate = false;
                    }
                }
                else
                {
                    //密码重设功能
                    IsValidate = (username == u && (useremail == e || mobile == m));
                }
                if (IsValidate)
                {
                    userinfo = DataTableToUserInfo(dt);
                    return true;
                }
                return false;
            }
            return false;

        }
        #endregion

        #region 用户登录
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="gid"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="vtype"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        internal static bool ValidateUser(int gid, string username, string password, ValidateType vtype, out FGBUserClass user)
        {
            return UserIsExist(gid, username, username, username, password, vtype, out user);
        }
        #endregion

        #region 验证cookie用户
        /// <summary>
        /// 验证cookie用户
        /// </summary>
        /// <param name="gid"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        internal static bool ValidateUser(int gid, int uid)
        {
            return CommonDataAccess.IsExist("select * from hfg_user where uid=" + uid + " and gid=" + gid + " and usrstatus=1");
        }

        #endregion

        #region 获取用户信息
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="gid">集团ID </param>
        /// <param name="uid">用户ID </param>
        /// <returns></returns>
        public static FGBUserClass GetUserInfo(int gid, int uid)
        {
            
             DataSet ds = CommonDataAccess.ExecProcedure
               ("HFG_UserInfo",
               "@gid,@uid",
               "int,int",
               new object[] { gid, uid });
             FGBUserClass userinfo = new FGBUserClass();
            userinfo=DataTableToUserInfo(ds.Tables[0]);
            DataTable dt=ds.Tables[1];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                FGBUserAddress address = new FGBUserAddress();
                address.adrid = (int)dt.Rows[i]["adrid"];
                address.uid = (int)dt.Rows[i]["uid"];
                address.adrtopics = dt.Rows[i]["adrtopics"].ToString();
                address.usrcountry = dt.Rows[i]["usrcountry"].ToString();
                address.usrprovince = dt.Rows[i]["usrprovince"].ToString();
                address.usrcity = dt.Rows[i]["usrcity"].ToString();
                address.adrcomment = dt.Rows[i]["adrcomment"].ToString();
                address.adrpost = dt.Rows[i]["adrpost"].ToString();
                address.adrtel = dt.Rows[i]["adrtel"].ToString();
                address.adrfax = dt.Rows[i]["adrfax"].ToString();
                address.adrcontact = dt.Rows[i]["adrcontact"].ToString();
                userinfo.Add(address);
            }
            return userinfo;
        }
        #endregion

        #region 用户表转用户对象
        /// <summary>
        /// 用户表转用户对象
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        private static FGBUserClass DataTableToUserInfo(DataTable dt)
        {
            FGBUserClass userinfo = new FGBUserClass();
            if (dt == null || dt.Rows.Count != 1)
            {
                return null;
            }
            userinfo.uid = (int)dt.Rows[0]["uid"];
            userinfo.gid = (int)dt.Rows[0]["gid"];

            userinfo.username = dt.Rows[0]["username"].ToString().Trim();
            userinfo.usrpassword = dt.Rows[0]["usrpassword"].ToString().Trim();
            userinfo.email = dt.Rows[0]["email"].ToString().Trim();
            userinfo.mobnumb = dt.Rows[0]["mobnumb"].ToString().Trim();
            userinfo.cardnumber = dt.Rows[0]["cardnumber"].ToString().Trim();

            userinfo.lvlid = (int)(FGBCommon.IsNull(dt.Rows[0]["lvlid"], typeof(int)));
            userinfo.endyear = (int)(FGBCommon.IsNull(dt.Rows[0]["endyear"], typeof(int)));
            userinfo.scores = (int)(FGBCommon.IsNull(dt.Rows[0]["scores"], typeof(int)));
            userinfo.usremail = dt.Rows[0]["usremail"].ToString().Trim();
            userinfo.emailformat = (byte)(FGBCommon.IsNull(dt.Rows[0]["emailformat"], typeof(byte)));
            userinfo.emaillanguage = (byte)(FGBCommon.IsNull(dt.Rows[0]["emaillanguage"], typeof(byte)));
            userinfo.usrmobile = dt.Rows[0]["usrmobile"].ToString().Trim();
            userinfo.question = (byte)(FGBCommon.IsNull(dt.Rows[0]["question"], typeof(byte)));
            userinfo.answer = dt.Rows[0]["answer"].ToString();
            userinfo.usrfirstname = dt.Rows[0]["usrfirstname"].ToString();
            userinfo.usrlastname = dt.Rows[0]["usrlastname"].ToString();
            userinfo.usrgender = (byte)(FGBCommon.IsNull(dt.Rows[0]["usrgender"], typeof(byte)));
            userinfo.usrbirthday = (DateTime)(FGBCommon.IsNull(dt.Rows[0]["usrbirthday"], typeof(DateTime)));
            userinfo.usrnationality = dt.Rows[0]["usrnationality"].ToString();
            userinfo.idtype = dt.Rows[0]["idtype"].ToString();
            userinfo.idno = dt.Rows[0]["idno"].ToString();
            userinfo.usrcountry = dt.Rows[0]["usrcountry"].ToString();
            userinfo.usrprovince = dt.Rows[0]["usrprovince"].ToString();
            userinfo.usrcity = dt.Rows[0]["usrcity"].ToString();
            userinfo.smoke = dt.Rows[0]["smoke"].ToString();
            userinfo.bed = dt.Rows[0]["bed"].ToString();
            userinfo.pillow = dt.Rows[0]["pillow"].ToString();
            userinfo.regdate = (DateTime)(FGBCommon.IsNull(dt.Rows[0]["regdate"], typeof(DateTime)));
            userinfo.logdate = (DateTime)(FGBCommon.IsNull(dt.Rows[0]["logdate"], typeof(DateTime)));
            userinfo.logip = dt.Rows[0]["logip"].ToString();
            userinfo.logcount = (int)(FGBCommon.IsNull(dt.Rows[0]["logcount"], typeof(int)));
            userinfo.usrstatus = (bool)dt.Rows[0]["usrstatus"];
            userinfo.emailcheck = (bool)(FGBCommon.IsNull(dt.Rows[0]["emailcheck"], typeof(bool)));
            userinfo.usercheckcode = dt.Rows[0]["usercheckcode"].ToString();
            userinfo.ademail = (bool)(FGBCommon.IsNull(dt.Rows[0]["ademail"], typeof(bool)));
            userinfo.admobile = (bool)(FGBCommon.IsNull(dt.Rows[0]["admobile"], typeof(bool)));
            userinfo.checkcodedate = (DateTime)(FGBCommon.IsNull(dt.Rows[0]["checkcodedate"], typeof(DateTime)));
            return userinfo;
        }
        #endregion

    


        /// <summary>
        /// 用户登陆日志
        /// </summary>
        /// <param name="uid">用户ID</param>
        /// <param name="IP">用户IP</param>
        /// <returns></returns>
        internal static LoginLog GetIPLog(int uid, string IP)
        {
            LoginLog log = new LoginLog();
            DataTable dt = CommonDataAccess.ExecProcedure
                ("HFG_User_Log",
                "@uid,@logip",
                "int,string",
                new object[] { uid, IP }, "vv");
            if (dt != null && dt.Rows.Count == 1)
            {
                log.logcount =(int) dt.Rows[0][0];
                log.logip = dt.Rows[0][1].ToString();
                log.logdate = (DateTime)dt.Rows[0][2];
            }
            return log;
        }
    }

    #region 枚举类型

    #region 用户校验方式
    /// <summary>
    /// 用户校验方式
    /// </summary>
    public enum ValidateType
    {
        /// <summary>
        /// 用户名方式
        /// </summary>
        UserName = 0,
        /// <summary>
        /// 邮箱方式
        /// </summary>
        Email = 1,
        /// <summary>
        /// 手机号方式
        /// </summary>
        Mobile = 2,
        /// <summary>
        /// 卡号
        /// </summary>
        CardNumber = 3

    }
    #endregion

    #region 用户cookie保存时间
    public enum CookieDays
    {
        unsave = 0,
        day = 1,
        week = 7,
        month = 30,
        year = 366
    }

    #endregion

    public class LoginLog
    {
        int _logcount = 0;
        string _logip = "首次登陆";
        DateTime _logdate;
        /// <summary>
        /// 登陆次数
        /// </summary>
        public int logcount
        {
            get { return _logcount; }
            set { _logcount = value; }
        }
        /// <summary>
        /// 登陆IP
        /// </summary>
        public string logip
        {
            get { return _logip; }
            set { _logip = value; }
        }
        /// <summary>
        /// 登陆时间
        /// </summary>
        public DateTime logdate
        {
            get { return _logdate; }
            set { _logdate = value; }
        }
    }


    #endregion
}
